package com.feinno.urcs.group.pd.servlet;

import com.feinno.cpim.CpimHeader;
import com.feinno.cpim.CpimMessage;
import com.feinno.sip.address.SipUri;
import com.feinno.sip.message.Content;
import com.feinno.urcs.content.Cpim;
import com.feinno.urcs.content.MimeType;
import com.feinno.urcs.content.UrcsMultipartMimeContent;
import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.api.GroupChatService;
import com.feinno.urcs.group.api.GroupService;
import com.feinno.urcs.group.siptask.task.GroupMessageArgs;
import com.feinno.urcs.nai.IMPU;
import com.feinno.urcs.profile.entity.ClientType;
import com.feinno.urcs.sipservlet.SipServlet;
import com.feinno.urcs.sipservlet.SipServletException;
import com.feinno.urcs.sipservlet.SipServletRequest;
import com.feinno.urcs.types.MobileNo;
import com.feinno.urcs.utils.SipHeaderUtils;
import com.feinno.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.address.SipURI;
import javax.sip.address.TelURI;
import javax.sip.address.URI;
import java.util.Iterator;

/**
 * groupId其他地方不是
 * <p>
 * Created by wuhao on 5/11/15.
 */
public class PdGroupPageModeServlet extends SipServlet {
	private static final Logger LOGGER = LoggerFactory.getLogger(PdGroupPageModeServlet.class);
	private GroupChatService groupChatService;
	private GroupService groupService;

	public void setGroupChatService(GroupChatService groupChatService) {
		this.groupChatService = groupChatService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	@Override
	protected void process(SipServletRequest sipServletRequest) throws SipServletException {
		LOGGER.info("PdGroupPageModeServlet process Begin");
		//检查群状态
//        if(!check(sipServletRequest)){
//            return;
//        }
		LOGGER.info("Group Page Mode Request:{}", sipServletRequest);
		GroupMessageArgs groupMessageArgs = parseRequestContent(sipServletRequest);
		LOGGER.info("groupMessageArgs.sender: {}", groupMessageArgs.getFromMobile());
		LOGGER.info("groupMessageArgs.groupid: {}", groupMessageArgs.getGroupId());
		LOGGER.info("groupMessageArgs.content: {}", new String(groupMessageArgs.getContent()));
		LOGGER.info("groupMessageArgs.contentType: {}", groupMessageArgs.getContentType());
		try {
			groupChatService.sendText(groupMessageArgs.getGroupId(), groupMessageArgs.getFromMobile(),
					groupMessageArgs.getContentType(), groupMessageArgs.getContent(), ClientType.PC, null, DateUtil.getUTCNow());
		} catch (Exception e) {
			LOGGER.error("PdGroupPageModeServlet SendText Error: {}", e);
		}
		sipServletRequest.sendResponse(202, "Accept");
		LOGGER.info("PdGroupPageModeServlet process End");
	}

	/**
	 * 检查消息
	 *
	 * @author wuhao
	 */
	private boolean check(SipServletRequest request) {
		LOGGER.info("PdGroupPageModeServlet check Begin");
		IMPU sender = SipHeaderUtils.getFromUser(request);
		IMPU grouper = SipHeaderUtils.getToUser(request);
		if (!grouper.toUri().isSipURI()) {
			request.sendResponse(404, "Group uri must be sip uri.");
			return false;
		}
		try {
			//检查群是否存在及其他状态
			groupService.check(MobileNo.parseFrom(sender.getUser()), getMobileNo(grouper.toUri()));
		} catch (Exception e) {
			// request.sendResponse(404, "group and sender url error");
			LOGGER.error("PdGroupLargeModeServlet check error {}", e);
			throw new RuntimeException(e);
		}
		LOGGER.info("PdGroupPageModeServlet check End");
		return true;
	}

	/**
	 * 解析消息体
	 *
	 * @author wuhao
	 */
	private GroupMessageArgs parseRequestContent(SipServletRequest sipServletRequest) {
		GroupMessageArgs groupMessageArgs = new GroupMessageArgs();
		String msgStr = "";
		IMPU sender = SipHeaderUtils.getFromUser(sipServletRequest);
		IMPU grouper = SipHeaderUtils.getToUser(sipServletRequest);
		groupMessageArgs.setFromMobile(MobileNo.parseFrom(sender.getUser()));
		// groupMessageArgs.setGroupId(URIUtils.getGroupIdFromUri(grouper.toUri().toString()));
		groupMessageArgs.setGroupId(getGroupIdFromUri("sip:1252002@feinno.com"));
		UrcsMultipartMimeContent ummc = sipServletRequest.getMultipartMimeContent();
		Cpim cpim = ummc.getContent(Cpim.class);
		if (cpim != null) {
			//根据CPIM查询状态报告
			try {
				CpimHeader contentType_header = cpim.getCpimMessage().getHeader("Content-Type");
				if (MimeType.parse(contentType_header.getValue()) == MimeType.IMDN) {
					CpimMessage infx = cpim.getCpimMessage();
				}
			} catch (Exception e) {
				LOGGER.error("PdGroupPageModeServlet parse content error" + e);
			}
		}
		Iterator<Content> iterator = ummc.getContents();
		Content connData;
		MimeType type;
		while (iterator.hasNext()) {
			connData = iterator.next();
			type = MimeType.parse(connData.getContentTypeHeader());
			switch (type) {

				case TextPlain:
				case TextHtml:
					msgStr = connData.getContentString();

					break;
				case CPIM:
					Cpim cpimData = (Cpim) connData;
					msgStr = cpimData.getCpimMessage().getContentString();
					break;
				default:
					msgStr = "";
					break;
			}
			groupMessageArgs.setContent(msgStr.getBytes());
			groupMessageArgs.setContentType(connData.getContentTypeHeader().getContentType());
		}
		return groupMessageArgs;
	}


	protected String getMobileNo(URI uri) {
		if (uri == null) {
			return null;
		} else if (uri.isSipURI()) {
			return ((SipUri) uri).getUser();
		} else {
			return "+" + ((TelURI) uri).getPhoneNumber();
		}
	}

	protected int getGroupIdFromUri(String groupUri) {
		URI uri = IMPU.parse(groupUri).toUri();
		if (uri.isSipURI()) {
			String gId = ((SipURI) uri).getUser().toString();
			return Integer.parseInt(gId.substring(GroupConfiguration.INSTANCE.getGroupPrefix().length()));
		} else {
			return 0;
		}
	}
}
